package com.talking.view.main;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.talking.App;
import com.talking.adapter.FriendOrGroupAdapter;
import com.talking.bean.FriendOrGroupBean;
import com.talking.bean.GroupBean;
import com.talking.bean.UserBean;
import com.talking.databinding.FragmentFriendBinding;
import com.talking.presenter.FriendPresenter;
import com.talking.presenter.GroupPresenter;
import com.talking.presenter.UserPresenter;
import com.talking.utils.Utils;
import com.talking.view.ChatGroupActivity;
import com.talking.view.PersonActivity;
import com.talking.view.VerityMsgActivity;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class FriendFragment extends Fragment {
    private FragmentFriendBinding binding;
    private FriendOrGroupAdapter adp;
    private final List<FriendOrGroupBean> data=new ArrayList<>();
    private int nowTab=0;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentFriendBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        binding.friendVerityMsg.setOnClickListener(v -> startActivity(new Intent(requireActivity(), VerityMsgActivity.class)));
        String msg = App.sp.getString("message", "");
        if (msg.contains("加好友")){
            binding.friendDot.setTextColor(Color.RED);
        }else{
            binding.friendDot.setTextColor(Color.BLACK);
        }
        adp=new FriendOrGroupAdapter(requireActivity(),data);
        binding.friendList.setAdapter(adp);
        binding.friendList.setOnItemClickListener((parent, view, position, id) -> {
            FriendOrGroupBean bean = data.get(position);
            if (bean.type.equals("friend")){
                UserPresenter.getUserByAccount(bean.friendAccount,null, new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                        requireActivity().runOnUiThread(() -> {
                            try {
                                JSONObject jo = new JSONObject(Objects.requireNonNull(response.body()).string());
                                App.userBean=new UserBean(jo.getString("nickname"),jo.getString("email"),bean.friendAccount,jo.getString("iconUrl"));
                                startActivity(new Intent(requireActivity(), PersonActivity.class));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }else {
                App.groupBean=new GroupBean(bean.groupname,bean.groupIcon,bean.groupId);
                startActivity(new Intent(requireActivity(), ChatGroupActivity.class));
            }
        });
        binding.friendTab.addTab(binding.friendTab.newTab().setText("好友"));
        binding.friendTab.addTab(binding.friendTab.newTab().setText("群组"));
        binding.friendTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (Objects.requireNonNull(tab.getText()).toString().equals("好友")){
                    nowTab=0;
                    refreshFriend();
                }else if (Objects.requireNonNull(tab.getText()).toString().equals("群组")){
                    nowTab=1;
                    refreshFriend();
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) { }
            @Override
            public void onTabReselected(TabLayout.Tab tab) { }
        });
        refreshFriend();
        return root;
    }
    private void refreshFriend() {
        if (nowTab==0) {
            FriendPresenter.query(App.sp.getString("account", ""), new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    requireActivity().runOnUiThread(() -> {
                        try {
                            String res = response.body().string();
                            if (res.equals("没得好友")) {
                                Utils.toast( res);
                            } else {
                                data.clear();
                                JSONArray ja = new JSONObject(res).getJSONArray("data");
                                for (int i = 0; i < ja.length(); i++) {
                                    JSONObject jo = ja.getJSONObject(i);
                                    data.add(new FriendOrGroupBean(jo.getString("friendAccount"), jo.getString("remark"),"friend",null,null,null));
                                }
                                adp.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
        }else {
            GroupPresenter.queryUser(App.sp.getString("account", ""), new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    requireActivity().runOnUiThread(() -> {
                        try {
                            data.clear();
                            String res = response.body().string();
                            if (res.equals("没有群")) {
                                Utils.toast( res);
                            } else {
                                JSONArray ja = new JSONObject(res).getJSONArray("data");
                                for (int i = 0; i < ja.length(); i++) {
                                    JSONObject jo = ja.getJSONObject(i);
                                    data.add(new FriendOrGroupBean(null,null,"group", jo.getString("name"), jo.getString("icon"), jo.getString("id")));
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        adp.notifyDataSetChanged();
                    });
                }
            });
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}